package com.xiaozhengkeji.blogsuper.api;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.xiaozhengkeji.blogsuper.base.entitys.FileCloudEntity;
import com.xiaozhengkeji.blogsuper.base.entitys.UserEntity;
import com.xiaozhengkeji.blogsuper.base.service.FileCloudEntityService;
import com.xiaozhengkeji.blogsuper.base.service.UserEntityService;
import com.xiaozhengkeji.blogsuper.bean.ResponseBean;
import com.xiaozhengkeji.blogsuper.bean.type.ResCodeType;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 文件传输Api
 */
@Slf4j
@RestController
@RequestMapping("/web/file")
public class FileApi {

    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Autowired
    private GridFSBucket gridFSBucket;
    @Autowired
    FileCloudEntityService fileCloudEntityService;
    @Autowired
    UserEntityService userEntityService;

    @ApiOperation("上传文件 需要登录")
    @PostMapping("/fileUpload")
    @SaCheckLogin
    public ResponseBean fileUpload(@RequestParam(value = "file", required = false) MultipartFile multipartFile) {
        UserEntity userEntity = userEntityService.selectByPrimaryKey(StpUtil.getLoginIdAsInt());
        // 获得提交的文件名
        String file_name = multipartFile.getOriginalFilename();
        //对文件名进行序列化
        if (file_name == null) file_name = UUID.randomUUID().toString();
        file_name = java.util.UUID.nameUUIDFromBytes(file_name.getBytes()).toString();
        try {
            // 获得文件输入流
            InputStream ins = multipartFile.getInputStream();
            // 获得文件类型
            String contentType = multipartFile.getContentType();
            // 将文件存储到mongodb中,mongodb 将会返回这个文件的具体信息
            ObjectId gfs = gridFsTemplate.store(ins, file_name, contentType);
            //将信息存储到Mysql中
            FileCloudEntity fileCloudEntity = new FileCloudEntity();
            fileCloudEntity.setFileName(multipartFile.getOriginalFilename());
            fileCloudEntity.setFileUUID(gfs.toString());
            fileCloudEntity.setFileSize(multipartFile.getSize());
            fileCloudEntity.setFileUser(userEntity.getEMailBox());
            fileCloudEntity.setContentType(contentType);
            fileCloudEntity.setCreatedTime(LocalDateTime.now());
            fileCloudEntity.setFileMD5("null");
            fileCloudEntityService.insert(fileCloudEntity);
            return new ResponseBean(ResCodeType.Success, "文件上传成功！", gfs.toString(), null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseBean(ResCodeType.Error, "文件上传失败！", null, null);
    }

    /**
     * 下载文件
     *
     * @param id
     * @param response
     * @return
     */
    @ApiOperation("下载文件 不需要登录 ID为上传文件时返回的ID")
    @GetMapping("/Download")
    public byte[] getFile(@RequestParam String id, HttpServletResponse response, HttpServletRequest request) {
        GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(id)));
        //打开下载流对象
        GridFSDownloadStream gridFS = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        //创建gridFsSource，用于获取流对象
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, gridFS);
        String fileName = "";
        FileCloudEntity fileCloudEntity = fileCloudEntityService.queryByFileUUID(id).get(0);
        fileName = fileCloudEntity.getFileName();
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            try {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            //非IE浏览器的处理：
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        // 通知浏览器进行文件下载
        response.setContentType(gridFsResource.getContentType());
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        try {
            return IOUtils.toByteArray(gridFsResource.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


}
